package com.hzy.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzy.admin.service.IMemberService;
import com.hzy.admin.domain.Member;
import com.hzy.admin.mapper.IMemberMapper;
import com.hzy.infrastructure.Tools;
import com.hzy.infrastructure.UploadFileUtil;
import com.hzy.infrastructure.domain.vo.PagingVo;
import com.hzy.system.domain.SysUser;
import com.hzy.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzy
 * @since 2020-04-28
 */
@Service
public class MemberServiceImpl extends ServiceImpl<IMemberMapper, Member> implements IMemberService {

    protected final ISysUserService sysUserService;

    public MemberServiceImpl(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public PagingVo<Map<String, Object>> findList(Integer page, Integer size, Member search) {
        Page<Map<String, Object>> iPage = new Page<>(page, size);
        List<Map<String, Object>> data = this.baseMapper.getList(iPage, search);
        return PagingVo.page(iPage, data);
    }

    @Override
    public Map<String, Object> findForm(String id) {
        Map<String, Object> map = new HashMap<>();

        Member model = Tools.nullSafe(this.baseMapper.selectById(id), new Member());
        SysUser user = this.sysUserService.getBaseMapper().selectById(model.getUserId());
        user = Tools.nullSafe(user, new SysUser());

        map.put("id", id);
        map.put("form", model);
        map.put("user", user);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveForm(Member form, final MultipartFile filePhoto, final MultipartFile[] files) {
        if (filePhoto != null) {
            try {
                form.setPhoto(UploadFileUtil.save(filePhoto));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (files != null && files.length > 0) {
            ArrayList<String> paths = new ArrayList<>();
            try {
                paths = UploadFileUtil.save(files);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!paths.isEmpty()) {
                form.setFilePath(Tools.joinString(paths, ","));
            }
        }

        this.saveOrUpdate(form);
        return form.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteList(List<String> ids) {
        this.removeByIds(ids);
    }
}
